package com.ls.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

//1+..+100 相加两个数差值超过10
class MyTask extends RecursiveTask<Integer> {

    //拆分差值不能超过10
    private static final Integer VALUE = 10;

    private int begin;//拆分开始值
    private int end;//拆分结束值
    private int result;//返回结果

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    //拆分和合并
    @Override
    protected Integer compute() {

        if (end - begin <= VALUE) {
            for (int i = begin; i <= end; i++) {
                result = result + i;
            }
        } else {
            int middle = (begin + end) / 2;
            MyTask myTask01 = new MyTask(begin, middle);
            MyTask myTask02 = new MyTask(middle+1, end);
            myTask01.fork();
            myTask02.fork();

            result = myTask01.join() + myTask02.join();
        }


        return result;
    }
}

public class Demo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask task = new MyTask(0, 100);
        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(task);
        Integer result = forkJoinTask.get();

        System.out.println(result);
        forkJoinPool.shutdown();
    }
}
